<template>
  <div id="promotionPage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <!-- 表格篩選 -->
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-button type="primary" @click="handleCreate">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
          <template v-if="column.dataIndex === 'priority'">
            <a-tooltip>
              <template #title>優先順序數字越大,執行優先級越高</template>
              <a-typography-text strong type="danger">優先級</a-typography-text>
              <QuestionCircleOutlined />
            </a-tooltip>
          </template>
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'promotionCardSet'">
            <a-popover title="折扣卡集合">
              <template #content>
                <!-- 匹配cardSetOptions -->
                <div v-for="desc in record.promotionCardDescSet" :key="desc">
                  <a-tag color="green">{{
                    // cardSetOptions.find((i: any) => i.key === item)?.label
                    desc
                  }}</a-tag>
                </div>
              </template>
              <a-tag
                color="#87d068"
                v-for="code in record.promotionCardSet"
                :key="code"
                >{{ code }}</a-tag
              >
            </a-popover>
          </template>
          <template v-if="column.dataIndex === 'reductionPlan'">
            <RouterLink
              :to="{
                name: 'RedictionPlanDetail',
                params: { id: record.reductionPlanId },
              }"
            >
              {{ record.reductionPlanTitle }}
            </RouterLink>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleEdit(record)">修改</a-button>
            <a-button danger @click="handleDelete(record)">刪除</a-button>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 新建模態框 -->
    <a-modal
      v-model:open="showModalCreate"
      title="新建自定義診金類型"
      :footer="null"
    >
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯自定義診金類型
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { customConsultTypeApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  filterFields,
  getCreteFieldConfig,
  getEditFieldConfig,
  // fetchCardSetOptions,
} from "@/models/customConsultType";
import { useRouter, useRoute } from "vue-router";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";

/******* 頁面狀態與配置 *****************************/
const breadcrumbItems = [{ url: "", name: "自定義診金類型" }];
const columns = tableColumns;
const filterConfig = filterFields;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// 分頁配置
const pagination = createPagination();

// 數據
const tableData = ref([]);
const editRecordId = ref<number>(0); // 當前編輯的自定義診金ID
const editFormData = reactive<any>({}); // 當前編輯的自定義診金數據
// const cardSetOptions = ref([]);

/******* 數據獲取與初始化 *****************************/
const fetchData = async (params?: any) => {
  loading.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await customConsultTypeApi.getCustomConsultTypeList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
    // if (cardSetOptions.value.length === 0) {
    //   cardSetOptions.value = await fetchCardSetOptions();
    // }
  } catch (error) {
    console.error("獲取自定義診金列表失敗", error);
  } finally {
    loading.value = false; // 結束加載
  }
};

watchRouteQuery(fetchData);

/******* 自定義診金操作處理 *****************************/
// 搜索
const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 新建
const showModalCreate = ref(false);
const handleCreate = async () => {
  showModalCreate.value = true;
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = await getCreteFieldConfig();
  }
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  try {
    await customConsultTypeApi.createCustomConsultType(data);
    message.success("創建自定義診金類型成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchData(route.query);
  } catch (error) {
    console.error("創建自定義診金失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 修改
const showModalEdit = ref(false);
const handleEdit = async (record: any) => {
  showModalEdit.value = true;
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = await getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  // 初始化編輯表單數據
  record.validDate = [record.validFrom, record.validTo];
  Object.assign(editFormData, record);
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    await customConsultTypeApi.updateCustomConsultType(
      editRecordId.value,
      data
    );
    message.success("修改自定義診金類型成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改自定義診金失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

// 查看
// const handleView = (record: any) => {
//   router.push({ name: "RedictionPlanDetail", params: { id: record.id } });
// };

// 刪除
const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除自定義診金 ${record.name} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await customConsultTypeApi.deleteCustomConsultType(record.id);
        message.success("刪除自定義診金類型成功");
        fetchData();
      } catch (error) {
        console.error("刪除自定義診金失敗:", error);
      }
    },
  });
};
</script>

<style scoped></style>
